<?php
declare (strict_types = 1);

namespace app\wxaizufang\controller;

use app\BaseController;
use app\middleware\CheckToken;
use app\test722\server\Token;
use app\wxaizufang\model\Fangattrs;
use app\wxaizufang\model\Images;
use app\wxaizufang\model\Price;
use app\wxaizufang\model\Purchase;
use app\wxaizufang\model\User;
use Firebase\JWT\JWT;
use think\Request;
use think\Response;

class WxLogin extends BaseController
{

    /**
     * Notes:
     * User: 大飞
     * Date: 2021/8/2
     * Time: 8:36
     */
   public function login(Request $request)
   {
       $code = $request->get('code');

       $apppId = "wx32e831fc5b1760b8";
       $AppSecret = "63e1c2674db78bdd7d4ab995a4de27e6";
       $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$apppId}&secret={$AppSecret}&js_code={$code}&grant_type=authorization_code";
       $res = $this->geturl($url);

       $userInfo = User::where('openid',$res['openid'])->find();
       //根据openidid查询数据库有没有该用户
       if ($userInfo)
       {

           $token = (new Token())->generateToken($userInfo['id']);
           return Response::create(['code'=>200,'msg'=>'请求成功!','token'=>$token],'json');
       }else{
          $userInfo =  User::create($res,true);

           $token = (new Token())->generateToken($userInfo['id']);

           return Response::create(['code'=>200,'msg'=>'请求成功!','token'=>$token],'json');
       }


   }


   //轮播图
    public function bannerImg()
    {
       $data =  Images::select();

     return  Response::create(['code'=>200,'msg'=>'请求成功!','data'=>$data],'json');

    }

    /**
     * Notes: 动态列表查询数据
     * User: 大飞
     * Date: 2021/8/2
     * Time: 11:26
     */
    public function dataSelect ()
    {
       $price = Price::select();
       $fangAttrs = Fangattrs::where('field_name','户型')->find()->value('id');
       $fangAttrs = Fangattrs::where('pid',$fangAttrs)->select()->toArray();

       return Response::create(['code'=>200,'msg'=>'请求成功!','price'=>$price,'fangAttrs'=>$fangAttrs],'json');


    }


    /**
     * Notes:出租信息添加
     * User: 大飞
     * Date: 2021/8/2
     * Time: 12:27
     * @param Request $request
     * @return Response
     */
    public function dataCreate(Request $request)
    {
        $data = $request->param();

       Purchase::create($data,true);

       return Response::create(['code'=>200,'msg'=>'添加成功'],'josn');
    }

   //get处理
   public function geturl($url)
   {
       $headerArray =array("Content-type:application/json;","Accept:application/json");
       $ch = curl_init();
       curl_setopt($ch, CURLOPT_URL, $url);
       curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
       curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
       curl_setopt($ch,CURLOPT_HTTPHEADER,$headerArray);
       $output = curl_exec($ch);
       curl_close($ch);
       $output = json_decode($output,true);
       return $output;
   }

}
